﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxTabControl;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxGridView;
using System.Configuration;
using System.Data;
using Wilson.ORMapper;
using Touchmax;


public partial class MastData_CustomerEdit : Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["Cust"] = "1=1";
        }
        if (Session["Cust"] != null)
        {
            this.dsList.FilterExpression = Session["Cust"].ToString();
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btn_Search_Click(object sender, EventArgs e)
    {
        string name = this.txt_Name.Text.Trim().ToUpper();
        string where = "";
        if (name.Length > 0)
        {
            where = string.Format("Name LIKE '%{0}%' OR Tel1 Like '%{0}%' OR Fax1 Like '%{0}%' OR Email1 Like '%{0}%' OR Contact1 Like '%{0}%'", name);
        }

        this.dsList.FilterExpression = where;
        this.gridList.DataBind();
        Session["Cust"] = where;
    }

    #region customer
    protected void gridList_Init(object sender, EventArgs e)
    {
        ASPxGridView grd = sender as ASPxGridView;
        if (grd != null)
        {
            grd.ForceDataRowType(typeof(Touchmax.BoClient));
        }
    }

    protected void gridEdit_Init(object sender, EventArgs e)
    {
        ASPxGridView grd = sender as ASPxGridView;
        if (grd != null)
        {
            grd.ForceDataRowType(typeof(Touchmax.BoClient));
        }
    }

    
    protected void gridEdit_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
    {

        e.NewValues["CustId"] = "0";
        e.NewValues["Address"] = " ";
        e.NewValues["Tel1"] = " ";
        e.NewValues["Tel2"] = " ";
        e.NewValues["Fax1"] = " ";
        e.NewValues["Fax2"] = " ";
        e.NewValues["Contact1"] = " ";
        e.NewValues["Contact2"] = " ";
        e.NewValues["Email1"] = " ";
        e.NewValues["Email2"] = " ";
        e.NewValues["Remark"] = " ";
        e.NewValues["NomInd"] = "N";
        e.NewValues["UeiNo"] = " ";

        string userId = HttpContext.Current.User.Identity.Name;
        e.NewValues["UserId"] = userId;
        e.NewValues["EntryDate"] = DateTime.Today;

    }
    protected void gridEdit_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {

        e.NewValues["CustId"] = GetNo("Cust").ToString();
        string userId = HttpContext.Current.User.Identity.Name;

        e.NewValues["UserId"] = userId;
        e.NewValues["EntryDate"] = DateTime.Today;
    }
    protected void gridEdit_RowInserted(object sender, DevExpress.Web.Data.ASPxDataInsertedEventArgs e)
    {
        if (e.Exception == null)
        {
            int custId = SafeValue.SafeInt(e.NewValues["CustId"], 0);
            if (custId > 0)
            {
                SetNewNo("Cust", custId);
            }
            Session["Cust"] = "CustId='" + custId + "'";
            this.dsEdit.FilterExpression = "CustId='" + custId + "'";
        }
    }
    protected void gridEdit_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {

    }
    protected void gridEdit_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
        
    }

    protected void gridEdit_CustomDataCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomDataCallbackEventArgs e)
    {
        string n = e.Parameters;
        dsEdit.FilterExpression = "CustId='"+n+"'";
        gridEdit.DataBind();
        //gridEdit.StartEdit(0);
        e.Result = n + " handled";
    }

    protected void gridEdit_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
        string n = e.Parameters;
        if (n == "Save")
        {
            ASPxPageControl pageControl = this.gridEdit.FindEditFormTemplateControl("pageControl") as ASPxPageControl;
            ASPxTextBox custIdCtr = pageControl.FindControl("ASPxTextBox6") as ASPxTextBox;
            // ASPxComboBox groupId = pageControl.FindControl("ASPxComboBox3") as ASPxComboBox;
            ASPxTextBox custName = pageControl.FindControl("ASPxTextBox1") as ASPxTextBox;
            ASPxTextBox custCode = pageControl.FindControl("ASPxTextBox23") as ASPxTextBox;
            ASPxMemo des = pageControl.FindControl("ASPxMemo1") as ASPxMemo;


            string userName = HttpContext.Current.User.Identity.Name;
            OPathQuery query = new OPathQuery(typeof(Touchmax.BoClient), "CustId='" + custIdCtr.Text + "'");
            Touchmax.BoClient cust = Touchmax.Manager.ORManager.GetObject(query) as Touchmax.BoClient;
            bool isNew = false;
            if (cust == null)
            {
                int custId = GetNo("CUSTOMER");

                isNew = true;
                cust = new Touchmax.BoClient();
                cust.CustId = custId.ToString();
                cust.UserId = HttpContext.Current.User.Identity.Name;
                cust.EntryDate = DateTime.Now;
            }
                cust.Code = custCode.Text;
                cust.Name = custName.Text;
                cust.Remark = des.Text;
            try
            {
                if (isNew)
                {
                    Manager.ORManager.StartTracking(cust, Wilson.ORMapper.InitialState.Inserted);
                    Manager.ORManager.PersistChanges(cust);
                    SetNewNo("CUSTOMER", SafeValue.SafeInt(cust.CustId, 0));
                }
                else
                {
                    Manager.ORManager.StartTracking(cust, Wilson.ORMapper.InitialState.Updated);
                    Manager.ORManager.PersistChanges(cust);
                }
            }
            catch
            {
            }
            Session["CustWhere"] = "CustId='" + cust.CustId + "'";
            this.dsEdit.FilterExpression = Session["CustWhere"].ToString();
            //if (this.gridEdit.GetRow(0) != null)
            //    this.gridEdit.StartEdit(0);
        }
        else
        {
            string[] cmd = n.Split(new char[] { '#' });
            if (cmd[0] == "Edit")
            {
                dsEdit.FilterExpression = "CustId='" + cmd[1] + "'";
                gridEdit.DataBind();
                //gridEdit.StartEdit(0);
            }
        }
    }



    public int GetNo(string counter_id)
    {
        string sql_ivNo = "select COUNTER from XXSETUP where CATEGORY='" + counter_id + "'";
        int _InvN = SafeValue.SafeInt(Touchmax.Manager.ORManager.ExecuteScalar(sql_ivNo), 0) + 1;
        return _InvN;
    }
    public void SetNewNo(string counter_id, int oldNo)
    {
        string sql_updateInvoiceN = string.Format("update xxsetup set COUNTER='{0}' where category='{1}'", oldNo, counter_id);
        int flag =Touchmax.Manager.ORManager.ExecuteCommand(sql_updateInvoiceN);
    } 
    #endregion

    #region Employee 
    protected void grd_Cont_Init(object sender, EventArgs e)
    {
        ASPxGridView grd = sender as ASPxGridView;
        if (grd != null)
        {
            grd.ForceDataRowType(typeof(Touchmax.BoClientContact));
        }
    }
    protected void grd_Cont_BeforePerformDataSelect(object sender, EventArgs e)
    {
        ASPxGridView grd = sender as ASPxGridView;
        if (grd != null && grd.GetMasterRowKeyValue() != null)
        {
            string custid = grd.GetMasterRowKeyValue().ToString();
            this.dsEmployee.FilterExpression = "CompanyId='" + custid + "'";// 

        }
    }
    protected void grd_Cont_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
    {
        //string oid = (sender as ASPxGridView).GetMasterRowKeyValue().ToString();
        //e.NewValues["ContNo"] = "";// order.ContNo;
        //e.NewValues["SealNo"] = "";//order.SealNo;
        //e.NewValues["Ft20"] = 0;
        //e.NewValues["Ft40"] = 0;
        //e.NewValues["Ft45"] = 0;
        //e.NewValues["FtType"] = "GP";
        //e.NewValues["ContStatus"] = "PENDING";
        //e.NewValues["ScheduleDate"] = new DateTime(1900,1,1);
        //e.NewValues["ScheduleTime"] = " ";
    }
    protected void grd_Cont_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        string custId = (sender as ASPxGridView).GetMasterRowKeyValue().ToString();
        e.NewValues["CompanyId"] = custId;
        e.NewValues["EmployeeId"] = GetNo("Employee");
        e.NewValues["UserId"] = HttpContext.Current.User.Identity.Name;
        e.NewValues["EntryDate"] = DateTime.Now;
    }
    protected void grd_Cont_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    { }
    protected void grd_Cont_RowInserted(object sender, DevExpress.Web.Data.ASPxDataInsertedEventArgs e)
    {
        if (e.Exception == null)
        {
            SetNewNo("Employee",SafeValue.SafeInt(e.NewValues["EmployeeId"],0));
        }
    }
    protected void grd_Cont_RowUpdated(object sender, DevExpress.Web.Data.ASPxDataUpdatedEventArgs e)
    {

    }
    #endregion

}
